package com.bartender.framework.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.bartender.common.core.domain.wx.WxUserInfo;
import com.bartender.common.core.domain.wx.WxSession;
import org.springframework.web.client.RestTemplate;
import com.bartender.common.core.redis.RedisCache;
import com.bartender.common.utils.SecurityUtils;
import com.bartender.common.utils.StringUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WxLoginService {

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @Value("${token.secret}")
    private String tokenSecret;

    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private RedisCache redisCache;

    private final RestTemplate restTemplate = new RestTemplate();

    public String login(String code) {
        String url = String.format(
            "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
            appid, secret, code);
        
        WxSession response = restTemplate.getForObject(url, WxSession.class);
        
        if (response != null && response.getOpenid() != null) {
            return generateToken(response.getOpenid());
        }
        
        throw new RuntimeException("微信登录失败");
    }

    public void updateUserInfo(WxUserInfo userInfo) {
        // 从token中获取openid
        String openid = SecurityUtils.getLoginUser().getUsername();
        if (StringUtils.isEmpty(openid)) {
            throw new RuntimeException("用户未登录");
        }

        // 将用户信息存入Redis，key为openid
        String userKey = "wx:user:" + openid;
        redisCache.setCacheObject(userKey, userInfo, expireTime, TimeUnit.MINUTES);
    }

    private String generateToken(String openid) {
        // 创建JWT token
        Map<String, Object> claims = new HashMap<>();
        claims.put("openid", openid);
        claims.put("loginTime", System.currentTimeMillis());

        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, tokenSecret)
                .compact();

        // 将token存入Redis
        String tokenKey = "wx:token:" + openid;
        redisCache.setCacheObject(tokenKey, token, expireTime, TimeUnit.MINUTES);

        return token;
    }

    /**
     * 验证token
     */
    public boolean validateToken(String token) {
        try {
            Map<String, Object> claims = Jwts.parser()
                    .setSigningKey(tokenSecret)
                    .parseClaimsJws(token)
                    .getBody();
            
            String openid = (String) claims.get("openid");
            String cachedToken = redisCache.getCacheObject("wx:token:" + openid);
            
            return token.equals(cachedToken);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token中获取openid
     */
    public String getOpenidFromToken(String token) {
        try {
            Map<String, Object> claims = Jwts.parser()
                    .setSigningKey(tokenSecret)
                    .parseClaimsJws(token)
                    .getBody();
            
            return (String) claims.get("openid");
        } catch (Exception e) {
            return null;
        }
    }
} 